<template>
    <div class="app-container">
        <el-card class="export-card">
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input v-model="FilePath" :readonly="StartType" placeholder="请输入文件路径"></el-input>
                </el-col>
                <el-col :span="6">
                    <el-button type="primary" :disabled="!FilePath" :loading="StartType" @click="startProcessClick">开始处理</el-button>
                    <el-button type="primary" @click="getFileList">刷新</el-button>
                </el-col>
                <!-- <el-button type="primary" @click="exportClick">导入文件</el-button> -->
            </el-row>
            <!-- <input type="file" webkitdirectory @change="directoryChange" class="file-input" ref="InputRef"> -->
            <div class="progress-container" v-if="StartType">
                <span>处理进度：</span>
                <el-progress :percentage="ProgressNum" >
                    <div >
                        {{(ProgressObj?.progress || 0) +'/' + (ProgressObj.all || 0)}}
                    </div>
                </el-progress>
            </div>
            <div style="margin-top: 30px;"></div>
            <el-table :data="TableData" style="width: 100%" height="80vh" v-loading="loading">
                <el-table-column prop="obj" label="文件路径" min-width="180"/>
                <el-table-column prop="stateStr" label="任务状态" min-width="120"></el-table-column>
                <el-table-column prop="ct" label="开始时间" min-width="200">
                    <template #default="scope">
                        {{scope.row.ct?moment(scope.row.ct).format('YYYY-MM-DD HH:mm:ss'):'--'}}
                    </template>
                </el-table-column>
                <el-table-column prop="oft" label="处理完成" min-width="200">
                    <template #default="scope">
                        {{scope.row.oft?moment(scope.row.oft).format('YYYY-MM-DD HH:mm:ss'):'--'}}
                    </template>
                </el-table-column>
                <el-table-column prop="ft" label="完成时间" min-width="200">
                    <template #default="scope">
                        {{scope.row.ft?moment(scope.row.ft).format('YYYY-MM-DD HH:mm:ss'):'--'}}
                    </template>
                </el-table-column>
                <el-table-column prop="cabinet" label="存储位置" min-width="200" show-overflow-tooltip >
                    <template #default="scope">
                        <el-tooltip
                            :content="scope.row.cabinetRemark"
                            :disabled="!scope.row.cabinetRemark"
                        >
                            {{scope.row.cabinet}}
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column  label="操作" width="120">
                    <template #default="scope">
                        <el-button type="text" @click="handleDownLoad(scope.row)" >详情</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <el-dialog :title="'详情'" v-model="dialogVisible" width="800px" :before-close="handleClose">
            <el-form :model="dialogData" label-width="100px" v-loading="dialogload">
                <el-form-item label="文件路径">
                    {{ dialogData.obj }}
                </el-form-item>
                <el-form-item label="任务状态">
                    {{ dialogData.stateStr }}
                </el-form-item>
                <el-form-item label="开始时间">
                    {{dialogData.ct?moment(dialogData.ct).format('YYYY-MM-DD HH:mm:ss'):'--'}}
                </el-form-item>
                <el-form-item label="处理完成">
                    {{dialogData.oft?moment(dialogData.oft).format('YYYY-MM-DD HH:mm:ss'):'--'}}
                </el-form-item>
                <el-form-item label="完成时间">
                    {{dialogData.ft?moment(dialogData.ft).format('YYYY-MM-DD HH:mm:ss'):'--'}}
                </el-form-item>
                <el-form-item label="存储位置">
                        <el-tooltip
                            :content="dialogData.cabinetRemark"
                            :disabled="!dialogData.cabinetRemark"
                        >
                            {{dialogData.cabinet}}
                        </el-tooltip>
                </el-form-item>
                <el-form-item label="合同数">
                    {{ dialogData.count }}
                </el-form-item>
                <el-form-item label="合同">
                    <el-table :data="dialogTable" border style="width: 100%"  >
                        <el-table-column prop="title" label="合同名称" min-width="180"/>
                        <el-table-column prop="page" label="页数" min-width="180"/>
                        <el-table-column prop="stateStr" label="状态" min-width="180"/>
                    </el-table>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElLoading, ElMessage } from 'element-plus';    // 导入 ElMessage
import axios from 'axios';
import moment from 'moment';
const loading = ref(false);
const dialogload = ref(false);
const dialogVisible = ref(false);
const InputRef = ref(null);
const StartType = ref(false);
const files = ref([]);
const dialogTable = ref([]);
const FilePath = ref('');
const TableData = ref([]);
const ProgressNum = ref(0);
const dialogData = ref({});
const ProgressObj = ref({
    
});
const handleDownLoad = (row) => {
    // downloadFile(path);
        // window.open('http://localhost:10899/file/download?fileId='+row.fileId);
    dialogVisible.value = true;
    getExportInfo(row)

}
console.log(process.env.NODE_ENV);

onMounted(() => {
    if(localStorage.getItem('GroupId')){
        StartType.value = true;
        getProgress();
    }else{
        getFileList();
    }
});
const handleClose = () => {
    dialogData.value = {};
    dialogVisible.value = false;
}
const getExportInfo = (row) => {
    dialogload.value = true;
    axios({
        method: 'post',
        url: import.meta.env.VITE_Request_Path+'/task/get',
        data: {
            id: row.id,
        },
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json',
        },
    }).then(res => {
        if(res.data.errorCode == 0){
            dialogData.value = res.data.data;
            dialogTable.value = res.data.data?.items;
        }else{
            dialogData.value = {};
            dialogTable.value = [];
            ElMessage.error(res.data.errorMsg);
        }
    }).catch(err => {
        ElMessage.error('获取合同详细失败!');
    }).finally(() => dialogload.value = false);
}

// 创建一个a标签，并做下载点击事件
const downloadFile = (str, fileName) => {
    const link = document.createElement("a");
    link.href = str;
    // link.download = fileName;
    // 此写法兼容可火狐浏览器
    document.body.appendChild(link);
    const evt = document.createEvent("MouseEvents");
    evt.initEvent("click", false, false);
    link.dispatchEvent(evt);
    document.body.removeChild(link);
}

const startProcessClick = () => {
    StartType.value = true;
    // axios.defaults.withCredentials = true;
    ElLoading.service({
        lock: true,
        text: '正在处理文件...',
        background: 'rgba(0, 0, 0, 0.7)'
    });
    axios({
        method: 'post',
        url: import.meta.env.VITE_Request_Path+'/contract/deal',
        data: {
            path: FilePath.value.replace(/\\/g, '\\\\'),
        },
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json',
        },
    }).then(res => {    
        if (res.data.errorCode == 0) {
            // 这里可以添加处理逻辑
            localStorage.setItem('GroupId', res.data.data);
            localStorage.setItem('FilePath', FilePath.value);
            ElMessage.success('文件提取完成，正在处理文件，请稍等...');
            getProgress();
        } else {
            ElMessage.error(res.data.errorMsg);
            StartType.value = false;
        }
        ElLoading.service().close();
    }).catch(err => {
        ElMessage.error('处理失败');
        StartType.value = false;
    });
};
const getProgress = () => {
    // axios.defaults.withCredentials = true;
    axios({
        method: 'post',
        url: import.meta.env.VITE_Request_Path+'/contract/file/deal/progress',
        data: {
            groupId: localStorage.getItem('GroupId'),
        },
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json',
        },
    }).then(async (res) => {
        if(res.data.errorCode == 0){
            ProgressNum.value =  res.data.data.all == 0 ? 0 : ((res.data.data.progress / res.data.data.all).toFixed(4) * 100).toFixed(2);
            ProgressObj.value.progress = res.data.data.progress;
            ProgressObj.value.all = res.data.data.all;
            if(res.data.data.progress == res.data.data.all && res.data.data.all != 0){
                StartType.value = false;
                FilePath.value = '';
                ElMessage.success('文件处理完成!');
                localStorage.removeItem('GroupId');
                localStorage.removeItem('FilePath');
            }else{
                setTimeout(async () => {
                    if(res.data.data.all != 0){
                        if(!StartType.value){
                            StartType.value = true;
                            FilePath.value = localStorage.getItem('FilePath');
                        }
                        getProgress();
                    }else{
                        StartType.value = false;
                        ElMessage.warning('文件处理进度异常！');
                        localStorage.removeItem('GroupId');
                    }
                    await getFileList();
                }, 1500);
            }
        }else{
            StartType.value = false;
            ElMessage.error(res.data.errorMsg);
            localStorage.removeItem('GroupId');
            localStorage.removeItem('FilePath');
        }
    }).catch(err => {
        ResMessage.error('文件处理失败!');
        StartType.value = false;
    });
}
const getFileList = () => {
    loading.value = true;
    axios({
        method: 'post',
        url: import.meta.env.VITE_Request_Path+'/task/list',
        data: {
            // page: 1,
            // size: 100,
        },
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json',
        },
    }).then(res => {
        if(res.data.errorCode == 0){
            TableData.value = res.data.data;
        }else{
            TableData.value = [];
            ElMessage.error(res.data.errorMsg);
            StartType.value = false;
        }
    }).catch(err => {
        ElMessage.error('获取文件列表失败!');
    }).finally(() => loading.value = false);
}
</script>

<style scoped lang="scss">
.file-input {
    display: none;
    opacity: 0;
}
.export-card{
    padding-top: 15px;
    .progress-container{
        margin: 30px 0;
        display: flex;
        align-items: center;
        .el-progress{
            flex: 1;
        }
    }
}
</style>